package cn.cdutetc.library.service.impl;

import cn.cdutetc.library.entity.pojo.BookCategory;
import cn.cdutetc.library.entity.pojo.BookItem;
import cn.hutool.core.bean.BeanUtil;
import cn.cdutetc.library.entity.dto.BookCreateDTO;
import cn.cdutetc.library.entity.dto.BookUpdateDTO;
import cn.cdutetc.library.entity.dto.BookVO;
import cn.cdutetc.library.entity.dto.BookImportDTO;
import cn.cdutetc.library.entity.dto.BookExportVo;
import cn.cdutetc.library.entity.enums.BookStatusEnum;
import cn.cdutetc.library.entity.pojo.Book;
import cn.cdutetc.library.common.exception.BizException;
import cn.cdutetc.library.common.ExcelUtils;
import cn.cdutetc.library.common.BookExcelAnalysisEventListener;
import cn.cdutetc.library.common.PoiExcelUtils;
import cn.cdutetc.library.common.CsvUtils;
import cn.cdutetc.library.mapper.BookCategoryMapper;
import cn.cdutetc.library.mapper.BookItemMapper;
import cn.cdutetc.library.mapper.BookMapper;
import cn.cdutetc.library.service.BookService;
import cn.cdutetc.library.service.BookItemService;
import cn.cdutetc.library.service.BookCategoryService;
import cn.cdutetc.library.entity.dto.BookCategoryDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图书服务实现类
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Autowired
    private BookCategoryMapper bookCategoryMapper;

    @Autowired
    private BookItemMapper bookItemMapper;
    
    @Autowired
    private BookItemService bookItemService;
    
    @Autowired
    private BookCategoryService bookCategoryService;
    

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createBook(BookCreateDTO createDTO) {
        // 检查ISBN是否存在
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsbn, createDTO.getIsbn());
        if (this.count(queryWrapper) > 0) {
            throw new BizException("ISBN已存在");
        }
        
        // 确保分类存在，如果不存在则自动创建
        Integer categoryId = ensureCategoryExists(createDTO.getCategoryName());
        
        // 创建图书
        Book book = new Book();
        BeanUtil.copyProperties(createDTO, book);
        book.setCategoryId(categoryId); // 设置分类ID
        book.setAvailableCopies(createDTO.getTotalCopies());
        
        
        // 保存图书
        this.save(book);
        
        // 创建图书条目
        List<BookItem> bookItems = new ArrayList<>();
        for (int i = 0; i < createDTO.getTotalCopies(); i++) {
            BookItem bookItem = new BookItem();
            bookItem.setBookId(book.getBookId());
            bookItem.setStatus(BookStatusEnum.IN_STOCK.getCode());
            bookItems.add(bookItem);
        }
        
        // 批量保存图书条目
        for (BookItem bookItem : bookItems) {
            bookItemMapper.insert(bookItem);
        }
        
        return book.getBookId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBook(BookUpdateDTO updateDTO) {
        // 检查图书是否存在
        Book book = this.getById(updateDTO.getBookId());
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 如果修改了ISBN，检查是否重复
        if (StringUtils.isNotBlank(updateDTO.getIsbn()) && !updateDTO.getIsbn().equals(book.getIsbn())) {
            LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Book::getIsbn, updateDTO.getIsbn());
            if (this.count(queryWrapper) > 0) {
                throw new BizException("ISBN已存在");
            }
        }
        
        // 如果修改了分类，检查分类是否存在
        if (StringUtils.isNotBlank(updateDTO.getCategoryName())) {
            LambdaQueryWrapper<BookCategory> categoryQueryWrapper = new LambdaQueryWrapper<>();
            categoryQueryWrapper.eq(BookCategory::getCategoryName, updateDTO.getCategoryName());
            BookCategory category = bookCategoryMapper.selectOne(categoryQueryWrapper);
            if (category == null) {
                throw new BizException("图书分类不存在");
            }
            book.setCategoryId(category.getCategoryId()); // 设置新的分类ID
        }
        
        // 更新图书
        BeanUtil.copyProperties(updateDTO, book);
        
        return this.updateById(book);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBook(Integer bookId) {
        // 检查图书是否存在
        Book book = this.getById(bookId);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 检查图书是否有借出的条目
        LambdaQueryWrapper<BookItem> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(BookItem::getBookId, bookId)
                .eq(BookItem::getStatus, BookStatusEnum.BORROWED.getCode());
        if (bookItemMapper.selectCount(itemQueryWrapper) > 0) {
            throw new BizException("该图书有借出的条目，无法删除");
        }
        
        // 删除图书条目
        LambdaQueryWrapper<BookItem> deleteItemWrapper = new LambdaQueryWrapper<>();
        deleteItemWrapper.eq(BookItem::getBookId, bookId);
        bookItemMapper.delete(deleteItemWrapper);
        
        // 删除图书
        return this.removeById(bookId);
    }

    @Override
    public BookVO getBookById(Integer bookId) {
        // 查询图书
        Book book = this.getById(bookId);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 转换为VO
        return convertToVO(book);
    }

    @Override
    public IPage<BookVO> pageBooks(Integer page, Integer size, String keyword, String categoryName) {
        // 构建查询条件
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索（书名、作者、ISBN、出版社）
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Book::getBookName, keyword)
                    .or().like(Book::getAuthor, keyword)
                    .or().like(Book::getIsbn, keyword)
                    .or().like(Book::getPublisher, keyword)
            );
        }
        
        // 分类筛选
        if (StringUtils.isNotBlank(categoryName)) {
            // 根据分类名称查找分类ID
            LambdaQueryWrapper<BookCategory> categoryQueryWrapper = new LambdaQueryWrapper<>();
            categoryQueryWrapper.eq(BookCategory::getCategoryName, categoryName);
            BookCategory category = bookCategoryMapper.selectOne(categoryQueryWrapper);
            if (category != null) {
                queryWrapper.eq(Book::getCategoryId, category.getCategoryId());
            } else {
                // 如果分类不存在，返回空结果
                queryWrapper.eq(Book::getCategoryId, -1);
            }
        }
        
        // 按图书名称排序
        queryWrapper.orderByAsc(Book::getBookName);
        
        // 分页查询
        Page<Book> bookPage = new Page<>(page, size);
        Page<Book> resultPage = this.page(bookPage, queryWrapper);
        
        // 转换为VO
        List<BookVO> bookVOList = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<BookVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(bookVOList);
        
        return voPage;
    }

    @Override
    public IPage<BookVO> pageBooks(Integer page, Integer size, String keyword, Integer categoryId) {
        // 构建查询条件
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索（书名、作者、ISBN、出版社）
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Book::getBookName, keyword)
                    .or().like(Book::getAuthor, keyword)
                    .or().like(Book::getIsbn, keyword)
                    .or().like(Book::getPublisher, keyword)
            );
        }
        
        // 分类筛选
        if (categoryId != null) {
            queryWrapper.eq(Book::getCategoryId, categoryId);
        }
        
        // 按图书名称排序
        queryWrapper.orderByAsc(Book::getBookName);
        
        // 分页查询
        Page<Book> bookPage = new Page<>(page, size);
        Page<Book> resultPage = this.page(bookPage, queryWrapper);
        
        // 转换为VO
        List<BookVO> bookVOList = resultPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<BookVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        voPage.setRecords(bookVOList);
        
        return voPage;
    }

    @Override
    public BookVO getBookByIsbn(String isbn) {
        // 查询图书
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsbn, isbn);
        Book book = this.getOne(queryWrapper);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 转换为VO
        return convertToVO(book);
    }
    
    /**
     * 根据ISBN检查图书是否存在
     */
    public BookVO checkBookExistsByIsbn(String isbn) {
        // 查询图书
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Book::getIsbn, isbn);
        Book book = this.getOne(queryWrapper);
        if (book == null) {
            return null; // 图书不存在，返回null
        }
        
        // 转换为VO
        return convertToVO(book);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean increaseStock(Integer bookId, Integer count) {
        if (count <= 0) {
            throw new BizException("增加数量必须大于0");
        }
        
        // 检查图书是否存在
        Book book = this.getById(bookId);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 增加图书库存
        book.setTotalCopies(book.getTotalCopies() + count);
        book.setAvailableCopies(book.getAvailableCopies() + count);
        this.updateById(book);
        
        // 创建图书条目
        List<BookItem> bookItems = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            BookItem bookItem = new BookItem();
            bookItem.setBookId(bookId);
            bookItem.setStatus(BookStatusEnum.IN_STOCK.getCode());
            bookItems.add(bookItem);
        }
        
        // 批量保存图书条目
        for (BookItem bookItem : bookItems) {
            bookItemMapper.insert(bookItem);
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean decreaseStock(Integer bookId, Integer count) {
        if (count <= 0) {
            throw new BizException("减少数量必须大于0");
        }
        
        // 检查图书是否存在
        Book book = this.getById(bookId);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 检查可用库存是否足够
        if (book.getAvailableCopies() < count) {
            throw new BizException("可用库存不足");
        }
        
        // 查询可用的图书条目
        LambdaQueryWrapper<BookItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookItem::getBookId, bookId)
                .eq(BookItem::getStatus, BookStatusEnum.IN_STOCK.getCode())
                .last("LIMIT " + count);
        List<BookItem> bookItems = bookItemMapper.selectList(queryWrapper);
        
        // 删除图书条目
        for (BookItem bookItem : bookItems) {
            bookItemMapper.deleteById(bookItem.getItemId());
        }
        
        // 减少图书库存
        book.setTotalCopies(book.getTotalCopies() - count);
        book.setAvailableCopies(book.getAvailableCopies() - count);
        this.updateById(book);
        
        return true;
    }
    
    /**
     * 将Book实体转换为BookVO
     * @param book 图书实体
     * @return 图书VO
     */
    private BookVO convertToVO(Book book) {
        if (book == null) {
            return null;
        }
        BookVO bookVO = new BookVO();
        BeanUtil.copyProperties(book, bookVO);
        
        // 查询分类名称
        BookCategory category = bookCategoryMapper.selectById(book.getCategoryId());
        if (category != null) {
            bookVO.setCategoryName(category.getCategoryName());
        }
        
        // 统计图书状态数量
        try {
            Map<String, Object> statusStats = getBookStatusStatistics(book.getBookId());
            Object statusStatisticsObj = statusStats.get("statusStatistics");
            
            if (statusStatisticsObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> statusStatistics = (Map<String, Object>) statusStatisticsObj;
                
                // 获取各状态的数量
                Object inStockInfoObj = statusStatistics.get("in_stock");
                Object borrowedInfoObj = statusStatistics.get("borrowed");
                Object abnormalInfoObj = statusStatistics.get("abnormal");
                
                Integer inStockCount = 0;
                Integer borrowedCount = 0;
                Integer abnormalCount = 0;
                
                if (inStockInfoObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> inStockInfo = (Map<String, Object>) inStockInfoObj;
                    Object countObj = inStockInfo.get("count");
                    if (countObj instanceof Integer) {
                        inStockCount = (Integer) countObj;
                    }
                }
                
                if (borrowedInfoObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> borrowedInfo = (Map<String, Object>) borrowedInfoObj;
                    Object countObj = borrowedInfo.get("count");
                    if (countObj instanceof Integer) {
                        borrowedCount = (Integer) countObj;
                    }
                }
                
                if (abnormalInfoObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> abnormalInfo = (Map<String, Object>) abnormalInfoObj;
                    Object countObj = abnormalInfo.get("count");
                    if (countObj instanceof Integer) {
                        abnormalCount = (Integer) countObj;
                    }
                }
                
                bookVO.setInStockCount(inStockCount);
                bookVO.setBorrowedCount(borrowedCount);
                bookVO.setAbnormalCount(abnormalCount);
            } else {
                // 如果获取失败，设置为0
                bookVO.setInStockCount(0);
                bookVO.setBorrowedCount(0);
                bookVO.setAbnormalCount(0);
            }
        } catch (Exception e) {
            log.warn("获取图书" + book.getBookId() + "状态统计失败: " + e.getMessage());
            // 如果获取失败，设置为0
            bookVO.setInStockCount(0);
            bookVO.setBorrowedCount(0);
            bookVO.setAbnormalCount(0);
        }
        
        return bookVO;
    }
    
    @Override
    public Map<String, Object> getBookStatusStatistics(Integer bookId) {
        // 检查图书是否存在
        Book book = this.getById(bookId);
        if (book == null) {
            throw new BizException("图书不存在");
        }
        
        // 获取状态统计
        Map<String, Integer> statusCount = bookItemService.getBookItemStatusCount(bookId);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("bookId", bookId);
        result.put("bookName", book.getBookName());
        result.put("totalCopies", book.getTotalCopies());
        result.put("availableCopies", book.getAvailableCopies());
        
        // 添加状态统计信息
        Map<String, Object> statusStatistics = new HashMap<>();
        for (Map.Entry<String, Integer> entry : statusCount.entrySet()) {
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("count", entry.getValue());
            BookStatusEnum statusEnum = BookStatusEnum.getByCode(entry.getKey());
            statusInfo.put("desc", statusEnum != null ? statusEnum.getDesc() : entry.getKey());
            statusStatistics.put(entry.getKey(), statusInfo);
        }
        result.put("statusStatistics", statusStatistics);
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBookItemStatus(Integer itemId, String status, String remark) {
        // 检查图书条目是否存在
        BookItem bookItem = bookItemMapper.selectById(itemId);
        if (bookItem == null) {
            throw new BizException("图书条目不存在");
        }
        
        // 验证状态是否有效
        BookStatusEnum statusEnum = BookStatusEnum.getByCode(status);
        if (statusEnum == null) {
            throw new BizException("无效的状态值");
        }
        
        // 更新状态
        boolean result = bookItemService.updateBookItemStatus(itemId, status, remark);
        
        if (result) {
            // 更新图书的可用数量统计
            updateBookAvailableCopies(bookItem.getBookId());
        }
        
        return result;
    }
    
    /**
     * 更新图书的可用数量统计
     * @param bookId 图书ID
     */
    private void updateBookAvailableCopies(Integer bookId) {
        // 统计在库状态的图书条目数量
        List<BookItem> availableItems = bookItemService.getBookItemsByBookIdAndStatus(
                bookId, BookStatusEnum.IN_STOCK.getCode());
        
        // 更新图书的可用数量
        Book book = this.getById(bookId);
        if (book != null) {
            book.setAvailableCopies(availableItems.size());
            this.updateById(book);
        }
    }
    
    
    
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importBooksFromPath(MultipartFile file) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                throw new BizException("上传文件不能为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                throw new BizException("文件格式不正确，请上传Excel文件(.xlsx或.xls)");
            }
            
            // 使用监听器读取Excel
            BookExcelAnalysisEventListener listener = new BookExcelAnalysisEventListener();
            List<BookImportDTO> bookList = ExcelUtils.readExcelFile(file.getInputStream(), BookImportDTO.class, listener);
            
            if (bookList == null || bookList.isEmpty()) {
                return "导入完成，共处理0条数据";
            }
            
            // 批量保存图书
            int successCount = 0;
            int failCount = 0;
            StringBuilder errorMsg = new StringBuilder();
            
            for (BookImportDTO importDto : bookList) {
                try {
                    // 检查ISBN是否已存在
                    BookVO existingBook = checkBookExistsByIsbn(importDto.getIsbn());
                    if (existingBook != null) {
                        // 如果图书已存在，增加库存
                        increaseStock(existingBook.getBookId(), importDto.getTotalCopies());
                        successCount++;
                        continue;
                    }
                    
                    // 创建新图书
                    BookCreateDTO createDTO = new BookCreateDTO();
                    createDTO.setIsbn(importDto.getIsbn());
                    createDTO.setBookName(importDto.getBookName());
                    createDTO.setAuthor(importDto.getAuthor());
                    createDTO.setPublisher(importDto.getPublisher());
                    createDTO.setPublishDate(importDto.getPublishDate());
                    createDTO.setCategoryName(importDto.getCategoryName());
                    createDTO.setPrice(importDto.getPrice());
                    createDTO.setTotalCopies(importDto.getTotalCopies());
                    createDTO.setLocation(importDto.getLocation());
                    createDTO.setDescription(importDto.getDescription());
                    
                    createBook(createDTO);
                    successCount++;
                    
                } catch (Exception e) {
                    failCount++;
                    errorMsg.append("ISBN: ").append(importDto.getIsbn())
                            .append(", 错误: ").append(e.getMessage()).append("; ");
                }
            }
            
            String result = String.format("导入完成！成功: %d条，失败: %d条", successCount, failCount);
            if (failCount > 0) {
                result += "。失败详情: " + errorMsg.toString();
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("批量导入图书失败", e);
            throw new BizException("批量导入失败: " + e.getMessage());
        }
    }
    
    @Override
    public String exportBooksToPath(String keyword) {
        try {
            // 查询图书数据
            List<BookVO> books = getAllBooks(keyword);
            
            if (books == null || books.isEmpty()) {
                throw new BizException("没有找到要导出的图书数据");
            }
            
            // 转换为导出VO
            List<BookExportVo> exportData = new ArrayList<>();
            for (BookVO book : books) {
                BookExportVo exportVo = new BookExportVo();
                exportVo.setBookId(book.getBookId());
                exportVo.setIsbn(book.getIsbn());
                exportVo.setBookName(book.getBookName());
                exportVo.setAuthor(book.getAuthor());
                exportVo.setPublisher(book.getPublisher());
                exportVo.setPublishDate(book.getPublishDate());
                exportVo.setCategoryName(book.getCategoryName());
                exportVo.setPrice(book.getPrice());
                exportVo.setTotalCopies(book.getTotalCopies());
                exportVo.setInStockCount(book.getInStockCount());
                exportVo.setBorrowedCount(book.getBorrowedCount());
                exportVo.setAbnormalCount(book.getAbnormalCount());
                exportVo.setLocation(book.getLocation());
                exportVo.setDescription(book.getDescription());
                exportData.add(exportVo);
            }
            
            // 生成文件名
            String fileName = "图书数据";
            if (keyword != null && !keyword.trim().isEmpty()) {
                fileName += "_筛选_" + keyword;
            }
            fileName += "_" + System.currentTimeMillis() + ".xlsx";
            
            // 保存到本地路径 - 硬编码路径
            String savePath = "D:\\tushuguanli\\images\\" + fileName;
            Boolean success = ExcelUtils.writeExcelFile(exportData, savePath, BookExportVo.class);
            
            if (success) {
                return savePath;
            } else {
                throw new BizException("保存文件失败");
            }
            
        } catch (Exception e) {
            log.error("导出图书到本地路径失败", e);
            throw new BizException("导出失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取所有图书（用于导出）
     */
    private List<BookVO> getAllBooks(String keyword) {
        // 这里需要实现获取所有图书的逻辑
        // 可以使用现有的分页查询方法，设置一个很大的页面大小
        IPage<BookVO> page = pageBooks(1, 10000, keyword, (String) null);
        return page.getRecords();
    }
    
    @Override
    public void downloadTemplate(HttpServletResponse response) {
        try {
            String fileName = "图书导入模板_" + System.currentTimeMillis();
            
            // 尝试使用POI生成Excel
            try {
                PoiExcelUtils.generateBookTemplate(response, fileName);
                return;
            } catch (Exception poiException) {
                log.warn("POI生成Excel失败，尝试使用CSV格式: " + poiException.getMessage());
            }
            
            // 如果POI失败，使用CSV格式
            CsvUtils.generateBookTemplateCsv(response, fileName);
            
        } catch (Exception e) {
            log.error("下载模板失败", e);
            throw new BizException("下载模板失败: " + e.getMessage());
        }
    }
    
    @Override
    public List<Map<String, Object>> getBookCategories() {
        try {
            List<BookCategory> categories = bookCategoryMapper.selectList(null);
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (BookCategory category : categories) {
                Map<String, Object> categoryMap = new HashMap<>();
                categoryMap.put("categoryId", category.getCategoryId());
                categoryMap.put("categoryName", category.getCategoryName());
                categoryMap.put("description", category.getDescription());
                result.add(categoryMap);
            }
            
            return result;
        } catch (Exception e) {
            log.error("获取图书分类列表失败", e);
            throw new BizException("获取图书分类列表失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer ensureCategoryExists(String categoryName) {
        if (StringUtils.isBlank(categoryName)) {
            throw new BizException("分类名称不能为空");
        }
        
        // 先查找分类是否存在
        LambdaQueryWrapper<BookCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BookCategory::getCategoryName, categoryName.trim());
        BookCategory existingCategory = bookCategoryMapper.selectOne(queryWrapper);
        
        if (existingCategory != null) {
            return existingCategory.getCategoryId();
        }
        
        // 分类不存在，创建新分类
        BookCategoryDTO categoryDTO = new BookCategoryDTO();
        categoryDTO.setCategoryName(categoryName.trim());
        categoryDTO.setDescription("通过图书导入自动创建的分类");
        
        try {
            return bookCategoryService.createCategory(categoryDTO);
        } catch (Exception e) {
            // 如果创建失败，可能是并发创建导致的重复，再次查询
            BookCategory category = bookCategoryMapper.selectOne(queryWrapper);
            if (category != null) {
                return category.getCategoryId();
            }
            throw new BizException("创建分类失败: " + e.getMessage());
        }
    }
}